<template>
  <div class="container">
    <!-- 图例 -->
    <div class="legend">
      <ul>
        <li>降雨点图例</li>
        <li>
          <p style="background-color: #840041"></p>
          >=250
        </li>
        <li>
          <p style="background-color: #850444"></p>
          100-250
        </li>
        <li>
          <p style="background-color: #ff00fe"></p>
          50-100
        </li>
        <li>
          <p style="background-color: #0001fc"></p>
          25-50
        </li>
        <li>
          <p style="background-color: #92bfe3"></p>
          10-25
        </li>
        <li>
          <p style="background-color: #3db93f"></p>
          0.1-10
        </li>
        <li>
          <p style="background-color: #a6f28e"></p>
          0
        </li>
        <li>单位：毫米</li>
      </ul>
    </div>
    <!-- 操作面板部分 -->
    <div class="right-part">
      <!-- 面雨量预报 -->
      <div class="title">
        <h4>
          <img
            style="height: 30px; vertical-align: middle; margin-top: -2px"
            src="@/assets/images/panel/trangle.png"
            alt=""
          />面雨量预报
        </h4>
      </div>
      <div class="form">
        <el-form ref="form" label-width="80px">
          <el-form-item label="起报时间">
            <el-date-picker
              style="width: 100%"
              v-model="selectTime"
              type="datetime"
              placeholder="请选择起报时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="时间间隔">
            <ul
              style="
                width: 100%;
                display: flex;
                justify-content: space-between;
                align-items: center;
                height: 40px;
              "
            >
              <li
                style="
                  width: 80px;
                  height: 25px;
                  text-align: center;
                  line-height: 25px;
                  background-color: #3c6485;
                  color: #fff;
                "
                v-for="(item, index) in selectTimeSpace"
                :class="selectTimeSpaceIndex == index ? 'select-validity' : ''"
                @click="selectTimeSpaceIndex = index"
              >
                {{ item.label }}
              </li>
            </ul>
          </el-form-item>
          <el-form-item label="时效">
            <el-select
              style="width: 100%"
              v-model="validity"
              placeholder="请选择"
            >
              <el-option
                v-for="item in validityOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="预报数据">
            <el-select
              style="width: 100%"
              v-model="yubaoDataType"
              placeholder="请选择"
            >
              <el-option
                v-for="item in yubaoDataTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="实况数据">
            <el-select
              style="width: 100%"
              v-model="skDataType"
              placeholder="请选择"
            >
              <el-option
                v-for="item in skDataTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <!-- 散点、色斑 -->
        <div class="point-part">
          <label>
            <input
              type="radio"
              name="1"
              id=""
              v-model="showType"
              value="散点"
            />散点
          </label>
          <label>
            <input
              type="radio"
              name="1"
              id=""
              v-model="showType"
              value="色斑"
            />色斑
          </label>
        </div>
      </div>
      <!-- 站点选择 -->
      <div class="title" style="border-top: 1px solid rgba(255, 255, 255, 0.5)">
        <h4>
          <img
            style="height: 30px; vertical-align: middle; margin-top: -2px"
            src="@/assets/images/panel/trangle.png"
            alt=""
          />站点选择
        </h4>
      </div>
      <div class="form">
        <el-form ref="form" :model="formData" label-width="80px">
          <el-form-item label="流域类型">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: space-between;
              "
            >
              <el-select
                v-model="basin"
                placeholder="请选择"
                @change="getFeature()"
              >
                <el-option
                  v-for="item in basinOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <el-button
                style="
                  border: 0;
                  border: 2px solid #1a65aa;
                  font-size: 14px;
                  width: 100px;
                  height: 25px;
                  background-color: #175387;
                  color: #fff;
                "
                >地图选择</el-button
              >
            </div>
          </el-form-item>
          <el-form-item label="检验方法">
            <el-select
              style="width: 100%"
              v-model="verificationMethod"
              placeholder="请选择"
            >
              <el-option
                v-for="item in verificationMethodOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="point-part">
          <label>
            <input
              type="radio"
              name="2"
              id=""
              value="合并检验"
              v-model="verificationWay"
            />合并检验
          </label>
          <label>
            <input
              type="radio"
              name="2"
              id=""
              v-model="verificationWay"
              value="单站检验"
            />单站检验
          </label>
        </div>
        <div class="btn">
          <p @click="query">查询检验</p>
          <p>评分结果</p>
        </div>
        <table
          border="1"
          cellspacing="0"
          style="border-collapse: collapse; border-color: #4987b9"
        >
          <tr>
            <td>预报类型</td>
            <td>评分</td>
          </tr>
          <tr v-for="item in 10" :key="item">
            <td>智能网格填报</td>
            <td>88</td>
          </tr>
        </table>
      </div>
    </div>
    <TestDialogVue v-if="dialogShow" @close="onClose" :series="series" :xAxisData="xAxisData"></TestDialogVue>
  </div>
</template>
<script>
import TestDialogVue from "./TestDialog.vue";
import { v4 as uuidv4 } from "uuid";
import moment from "moment";
import {Vector} from 'ol/layer'
import {Vector as VectorSource} from 'ol/source'
import { Feature } from "ol";
import {Point,Polygon} from 'ol/geom'
import {Style,Fill,Circle,Text} from 'ol/style'
import * as echarts  from 'echarts';
//预报的接口
import {
  //中小河流域
  getRiverRainYbWithShuZhi,
  getRiverRainYbWithYanSe,
  //山洪沟
  getGullyRainYbShuZhi,
  getGullyRainYbYanSe,
  //水库上游面雨量预报
  getReservoirRainYbShuzhi,
  getReservoirRainYbYanSe,
  //主要河流
  getMainRiverShuzhi,
  getMainRiverYanSe,
  //行政区
  getadministrativeRegionShuZhi,
  getadministrativeRegionYanSe,
  //地址灾害
  getdzPotentialPointsRainYbShuZhi,
  getdzPotentialPointsRainYbYanSe,
  //洪水灾害隐患点
  getshPotentialPointsRainYbShuzhi,
  getshPotentialPointsRainYbYanSe,
} from "@/api/zhjcright";
//实况的接口
import {
  //中小河流域
  getriverRainSkShuzhi,
  getriverRainSkYanSe,
  //山洪沟
  getGullyRainSkShuZhi,
  getGullyRainSkYanSe,
  //水库上游面雨量预报
  getReservoirRainSkShuZhi,
  getReservoirRainSkYanse,
  //主要河流
  getMainRiverSKShuZhi,
  getMainRiverSKYanSe,
  //行政区
  getAdministrativeRegionSKShuZhi,
  getAdministrativeRegionSKYanse,
  //地址灾害
  getdzPotentialPointsRainSkShuZhi,
  getdzPotentialPointsRainSkYanse,
  //洪水灾害隐患点
  getshPotentialPointsRainSkShuZhi,
  getshPotentialPointsRainSkYanse,
} from "@/api/zhjcright";
import {queryVerificationAndEvaluation} from '@/api/pgjy'
export default {
  components: {
    TestDialogVue,
  },
  data() {
    return {
      selectTime: new Date(2024,0,1,0,0,0),
      dialogShow: false,
      formData: {},
      //流域选择
      basinOptions: [
        {
          id: uuidv4(),
          value: "中小河流",
          label: "中小河流",
        },
        {
          id: uuidv4(),
          value: "山洪沟",
          label: "山洪沟",
        },
        {
          id: uuidv4(),
          value: "水库上游集水区",
          label: "水库上游集水区",
        },
        {
          id: uuidv4(),
          value: "主要河流",
          label: "主要河流",
        },
        {
          id: uuidv4(),
          value: "地灾隐患点",
          label: "地灾隐患点",
        },
        {
          id: uuidv4(),
          value: "山洪隐患点",
          label: "山洪隐患点",
        },
      ],
      basin: "",
      //预报数据源
      yubaoDataType: "EC网格",
      yubaoDataTypeOptions: [
        {
          id: uuidv4(),
          value: "网格",
          label: "ECMEF",
        },
        {
          id: uuidv4(),
          value: "智能网格",
          label: "智能网格",
        },
      ],
      // 实况数据源
      skDataType: "站点实况",
      skDataTypeOptions: [
        {
          id: uuidv4(),
          value: "站点实况",
          label: "站点实况",
        },
        {
          id: uuidv4(),
          value: "融合网格",
          label: "融合网格",
        },
      ],
      //时间间隔
      selectTimeSpaceIndex: 0,
      selectTimeSpace: [
        {
          label: "1小时",
          value: "1",
          id: uuidv4(),
        },
        {
          label: "3小时",
          value: "3",
          id: uuidv4(),
        },
        {
          label: "12小时",
          value: "12",
          id: uuidv4(),
        },
        {
          label: "24小时",
          value: "24",
          id: uuidv4(),
        },
      ],
      //时效
      //时效
      validity: "1",
      //色变或者散点
      showType: "散点",
      //校验方法
      verificationMethodOptions: [
        {
          id: uuidv4(),
          value: "绝对插值",
          label: "绝对插值",
        },
        {
          id: uuidv4(),
          value: "模糊评分",
          label: "模糊评分",
        },
      ],
      verificationMethod: "绝对插值",
      //校验的方式
      verificationWay: "合并检验",
      shuzhiLayer: null,
      fillColorLayer: null,
      //单点查询时的区域的名字
      areaName:"",
      //图表的x轴数据
      xAxisData:[],
      series:[],
    };
  },
  computed: {
    validityOptions() {
      const options = [];
      //1小时的间隔
      for (let i = 1; i <= 168; i++) {
        options.push({
          value: i + "",
          label: i + "",
        });
      }
      return options;
    },
  },
  mounted() {
    this.shuzhiLayer = new Vector({
      source: new VectorSource({}),
      zIndex: 30,
      name: "pinggujiaoyan-sandian-layer",
    });
    this.fillColorLayer = new Vector({
      source: new VectorSource({}),
      name: "pinggujiaoyan-seban-layer",
      zIndex: 25,
    });
    const map = this.$store.getters.Map.map;
    map.addLayer(this.fillColorLayer);
    map.addLayer(this.shuzhiLayer);
    map.on("click",this.getFeatureByClick)
  },
  beforeDestroy(){
    this.fillColorLayer && this.$store.getters.Map.map.removeLayer(this.fillColorLayer);
    this.shuzhiLayer && this.$store.getters.Map.map.removeLayer(this.shuzhiLayer);
    this.$store.getters.Map.map.un("click",this.getFeatureByClick);
  },
  methods: {
    //查询的结果
    async query() {
      let formatter = "YYYY-MM-DD HH:mm:ss";
      //计算开始的时间
      if (this.selectTime) {
        const startTime = moment(this.selectTime).format(formatter);
        const hour = parseInt(
          this.selectTimeSpace[this.selectTimeSpaceIndex].value
        );
        let nextTime = new Date(
          this.selectTime.getTime() + hour * 60 * 60 * 1000
        );
        let endTime = moment(nextTime).format(formatter);
        const option = {
          startTime: startTime,
          endTime: endTime,
          skType: this.skDataType,
          ybType: this.yubaoDataType,
          nTimes: this.validity,
          quName: this.basin,
          filterType: this.verificationMethod == "绝对插值" ? "1" : "2",
        };
        if(this.verificationWay == '单站检验'){
          option.areaName = this.areaName;
        }
        console.log(option);
        const res = await queryVerificationAndEvaluation(option);
        console.log(res);
        if(res.data){
          const names = [];
          const series = [];
          const date = [];
          for(let key in res.data){
            names.push(key);
            const data = [];
            res.data[key].forEach(item=>{
              date.push(item.time);
              data.push(parseFloat(item.absoluteError.toFixed(2)));
            });
            const serie = {
              data:data,
              name:key,
              type: 'line',
						smooth: true,
						color: "#" + (Math.floor(Math.random() * 16777216)).toString(16).padStart(6, '0'),
						areaStyle: {
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
									offset: 0,
									color: '#cf9e2a'
								},
								{
									offset: 1,
									color: 'rgba(8, 46, 82, 0.8)'
								}
							])
						},
            }
            series.push(serie);
          }
          this.xAxisData = date.filter((item,index)=>date.indexOf(item) == index).sort((a,b)=>{
            return new Date(a) - new Date(b);
          })
          console.log(this.xAxisData);
          this.series = series;
        }
        this.dialogShow = true;
      }
    },
    //获取评分的结果
    onClose() {
      this.dialogShow = false;
    },

    //点击获取要素
    getFeatureByClick(e){
      const feature = this.$store.getters.Map.map.forEachFeatureAtPixel(e.pixel, (feature, layer) => {
        return feature;
      });
      if (feature) {
        this.areaName = feature.get("name");
        console.log(this.areaName);
      }
    },
    //利于选中的时添加要素
    async getFeature() {
      let formatter = "YYYY-MM-DD HH:mm:ss";
      console.log(this.basin);
      //计算开始的时间
      if (this.selectTime) {
        const startTime = moment(this.selectTime).format(formatter);
        const hour = parseInt(
          this.selectTimeSpace[this.selectTimeSpaceIndex].value
        );
        let nextTime = new Date(
          this.selectTime.getTime() + hour * 60 * 60 * 1000
        );
        let endTime = moment(nextTime).format(formatter);
        const option = {
          startTime: startTime,
          endTime: endTime,
          type: this.yubaoDataType,
          nTimes: parseInt(this.validity),
        };
        console.log(option);
        console.log(this.basin);
        //中小河流域
        if (this.basin == "中小河流") {
          await this.addFeatureToMap(
            [
              getRiverRainYbWithShuZhi,
              getRiverRainYbWithYanSe,
              getriverRainSkShuzhi,
              getriverRainSkYanSe,
            ],
            option
          );
        } else if (this.basin == "山洪沟") {
          await this.addFeatureToMap(
            [
              getGullyRainYbShuZhi,
              getGullyRainYbYanSe,
              getGullyRainSkShuZhi,
              getGullyRainSkYanSe,
            ],
            option
          );
        } else if (this.basin == "水库上游集水区") {
          await this.addFeatureToMap(
            [
              getReservoirRainYbShuzhi,
              getReservoirRainYbYanSe,
              getReservoirRainSkShuZhi,
              getReservoirRainSkYanse,
            ],
            option
          );
        } else if (this.basin == "主要河流") {
          option.river = parseInt(Math.random() * 10);
          await this.addFeatureToMap(
            [
              getMainRiverShuzhi,
              getMainRiverYanSe,
              getMainRiverSKShuZhi,
              getMainRiverSKYanSe,
            ],
            option
          );
        } else if (this.basin == "地灾隐患点") {
          await this.addFeatureToMap(
            [
              getdzPotentialPointsRainYbShuZhi,
              getdzPotentialPointsRainYbYanSe,
              getdzPotentialPointsRainSkShuZhi,
              getdzPotentialPointsRainSkYanse,
            ],
            option
          );
        } else if (this.basin == "山洪隐患点") {
          await this.addFeatureToMap(
            [
              getshPotentialPointsRainYbShuzhi,
              getshPotentialPointsRainYbYanSe,
              getshPotentialPointsRainSkShuZhi,
              getshPotentialPointsRainSkYanse,
            ],
            option
          );
        }
      }
    },
    //添加要素
    async addFeatureToMap(funcionsArr, option) {
      if (this.showType == "散点") {
        const shuzhiYB = await funcionsArr[0](option);
        this.addTextToMap(shuzhiYB);
        option.type = this.skDataType;
        const shuzhiSK = await funcionsArr[2](option);
        this.addTextToMap(shuzhiSK);
      } else if (this.showType == "色斑") {
        const yanseYB = await funcionsArr[1](option);
        this.addFillColor(yanseYB);
        option.type = this.skDataType;
        const yanseSk = await funcionsArr[3](option);
        this.addFillColorSK(yanseSk);
      }
    },
    //添加散点
    addTextToMap(shuzhi) {
      console.log("数值", JSON.stringify(shuzhi.data));
      this.shuzhiLayer.getSource().clear();
      let lat;
      let lng;
      shuzhi.data.forEach((itemShuZhi) => {
        lat = parseFloat(itemShuZhi.longitude);
        lng = parseFloat(itemShuZhi.latitude);
        const feature = new Feature({
          geometry: new Point([lat, lng]),
        });
        for(let key in itemShuZhi){
          feature.set(key,itemShuZhi[key]);
        }
        feature.setStyle(
          new Style({
            text: new Text({
              offsetX: 0,
              offsetY: 10,
              font: "normal 16px 微软雅黑",
              text: itemShuZhi.arearain + "",
              fill: new Fill({
                color: "#2394FF",
              }),
            }),
          })
        );
        this.shuzhiLayer.getSource().addFeature(feature);
      });
      this.$store.getters.Map.view.animate({
        center: [lat, lng],
      });
    },

    //添加填色图层 == 预报
    addFillColor(yanse) {
      console.log("填色", JSON.stringify(yanse.data));
      this.fillColorLayer.getSource().clear();
      const colors = yanse.data.areaRainLV.map((itemColor) =>
        itemColor.elementcolor.toString(16).padStart(6, "0")
      );
      yanse.data.areaRainYB.forEach((itemYanse, index) => {
        let feature;
        if (itemYanse.basinPerimeterArray) {
          feature = new Feature({
            geometry: new Polygon([itemYanse.basinPerimeterArray]),
            name: itemYanse.name,
          });
          for(let key in itemYanse){
            feature.set(key,itemYanse[key]);
          }
          feature.setStyle(
            new Style({
              fill: new Fill({
                color: "#" + colors[index],
              }),
            })
          );
        } else {
          const lat = parseFloat(itemYanse.longitude);
          const lng = parseFloat(itemYanse.latitude);
          feature = new Feature({
            geometry: new Point([lat, lng]),
            name: itemYanse.name,
          });
          for(let key in itemYanse){
            feature.set(key,itemYanse[key]);
          }
          feature.setStyle(
            new Style({
              image: new Circle({
                fill: new Fill({
                  color: "#" + colors[index],
                }),
                radius: itemYanse.arearain * 2,
              }),
            })
          );
        }

        this.fillColorLayer.getSource().addFeature(feature);
      });
    },

    //实况的填色
    addFillColorSK(yanse) {
      console.log(yanse);
      this.fillColorLayer.getSource().clear();
      const colors = yanse.data.areaRainLV.map((itemColor) =>
        itemColor.elementcolor.toString(16).padStart(6, "0")
      );
      yanse.data.areaRainSK.forEach((itemYanse, index) => {
        let feature;
        if (itemYanse.basinPerimeterArray) {
          feature = new Feature({
            geometry: new Polygon([itemYanse.basinPerimeterArray]),
            name: itemYanse.name,
          });
          for(let key in itemYanse){
            feature.set(key,itemYanse[key]);
          }
          feature.setStyle(
            new Style({
              fill: new Fill({
                color: "#" + colors[index],
              }),
            })
          );
        } else {
          const lat = parseFloat(itemYanse.longitude);
          const lng = parseFloat(itemYanse.latitude);
          feature = new Feature({
            geometry: new Point([lat, lng]),
            name: itemYanse.name,
          });
          for(let key in itemYanse){
            feature.set(key,itemYanse[key]);
          }
          feature.setStyle(
            new Style({
              image: new Circle({
                fill: new Fill({
                  color: "#" + colors[index],
                }),
                radius: itemYanse.arearain * 2,
              }),
            })
          );
        }

        this.fillColorLayer.getSource().addFeature(feature);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
}
ul {
  list-style: none;
}
.container {
  width: 100%;
  height: 100vh;
  // 图例样式
  .legend {
    color: #fff;
    // width: 100px;
    padding: 0 10px;
    // height: 260px;
    position: absolute;
    background-color: rgba(8, 46, 82, 0.8);
    z-index: 1;
    left: 10px;
    bottom: 140px;
    ul {
      li {
        display: flex;
        align-items: center;
        margin: 10px 0;
        font-size: 14px;
        p {
          width: 14px;
          height: 14px;
          border-radius: 100%;
          margin-right: 5px;
          border: 1px solid #fff;
        }
      }
    }
  }
  //操作面板部分样式
  .right-part {
    width: 440px;
    position: absolute;
    background-color: rgba(8, 46, 82, 0.8);
    z-index: 1;
    right: 10px;
    top: 0;
    .title {
      height: 30px;
      line-height: 30px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.5);
      background-image: url("../../assets/images/panel/panel-bottom-left.png");
      background-repeat: no-repeat;
      background-size: 100%;
      color: #fff;
    }
    .form {
      padding: 10px;
      ::v-deep(.el-form-item__label) {
        color: #fff;
      }
      ::v-deep(.el-input__inner) {
        height: 25px;
        line-height: 25px;
        background-color: #3c6485;
        border: 0;
        border-radius: 0;
        color: #fff;
      }
      .point-part {
        color: #fff;
        font-size: 14px;
        label {
          margin-right: 25px;
        }
        input {
          vertical-align: middle;
          margin-right: 5px;
          margin-top: -3px;
        }
      }
      .btn {
        margin: 10px 0;
        display: flex;
        justify-content: space-evenly;
        p {
          width: 100px;
          height: 35px;
          background-color: #175387;
          color: #fff;
          text-align: center;
          line-height: 35px;
          font-size: 15px;
          border: 1px solid #1a65aa;
        }
      }
      table {
        width: 100%;
        tr {
          &:nth-child(1) {
            td {
              background-color: #254f71;
            }
          }
          td {
            width: 50%;
            height: 30px;
            line-height: 30px;
            text-align: center;
            font-size: 14px;
            color: #fff;
            background-color: #184366;
          }
        }
      }
    }
  }
}
.select-validity {
  background-color: #1a65aa !important;
}
</style>
